package com.cn.ycy.hystrix;

import org.junit.Test;
import rx.Observable;
import rx.Observer;
import rx.functions.Action1;

import java.util.concurrent.Future;

import static org.junit.Assert.assertEquals;

public class HystrixTest {


  @org.junit.Test
  public void testSynchronous() {
    CommandHelloWorld world1 = new CommandHelloWorld("World");
    // execute() 调用的是 Future 的 get() 方法。
    String world = world1.execute();
    assertEquals("Hello World!", world);
    assertEquals("Hello Bob!", new CommandHelloWorld("Bob").execute());
  }

  @Test
  public void testAsynchronous1() throws Exception {
    assertEquals("Hello World!", new CommandHelloWorld("World").queue().get());
    assertEquals("Hello Bob!", new CommandHelloWorld("Bob").queue().get());
  }

  @Test
  public void testObservable() throws Exception {

    CommandHelloWorld world = new CommandHelloWorld("World");
    Observable<String> fWorld = world.observe();

    // blocking
    String single = fWorld.toBlocking().single();
    System.out.println(single);
    assertEquals("Hello World!", single);

    Observable<String> fBob = new CommandHelloWorld("Bob").observe();
    String single1 = fBob.toBlocking().single();
    assertEquals("Hello Bob!", single1);

    // non-blocking
    // - this is a verbose anonymous inner-class approach and doesn't do assertions
    fWorld.subscribe(new Observer<String>() {

      @Override
      public void onCompleted() {
        // nothing needed here
      }

      @Override
      public void onError(Throwable e) {
        e.printStackTrace();
      }

      @Override
      public void onNext(String v) {
        System.out.println("onNext: " + v);
      }

    });

    // non-blocking
    // - also verbose anonymous inner-class
    // - ignore errors and onCompleted signal
    fBob.subscribe(new Action1<String>() {

      @Override
      public void call(String v) {
        System.out.println("onNext: " + v);
      }

    });

    // non-blocking
    // - using closures in Java 8 would look like this:

    //            fWorld.subscribe((v) -> {
    //                System.out.println("onNext: " + v);
    //            })

    // - or while also including error handling

    //            fWorld.subscribe((v) -> {
    //                System.out.println("onNext: " + v);
    //            }, (exception) -> {
    //                exception.printStackTrace();
    //            })

    // More information about Observable can be found at https://github.com/Netflix/RxJava/wiki/How-To-Use

  }

}
